<?php
/**
 * Plugin Name: BSC Custom Field Search
 * Plugin URI: http://www.bridgesytem.me
 * Description: BSC Custom Field Search for Creation Site
 * Version: 1.2
 * Author: Tran Cuong Truc
 * Author URI: http://www.trancuongtruc.net
 * License: Private GPL2
 */
define("BSC_CFS_URL", path_join(WP_PLUGIN_URL,basename(dirname(__FILE__))));
define("BSC_CFS_TABLE_NAME","wp_bsc_custom_search");
define("BSC_CFS_VERSION","1.2");

function plugin_installation() {
	global $wpdb;
	if($wpdb->get_var("SHOW TABLES LIKE '".BSC_CFS_TABLE_NAME."'") != BSC_CFS_TABLE_NAME) {
		$sql = "CREATE TABLE ".BSC_CFS_TABLE_NAME." (
				id INTEGER(11) AUTO_INCREMENT,
				field_name VARCHAR(255),
				data TEXT,
				type VARCHAR(255),
				custom_field_name VARCHAR(255),
				PRIMARY KEY (id) )
				CHARACTER SET UTF8";
		require_once(ABSPATH . "/wp-admin/includes/upgrade.php");
		dbDelta($sql);
		add_option("BSC_CFS_PLUGIN_VER",BSC_CFS_VERSION);	
	}
	$current_version = get_option("BSC_CFS_PLUGIN_VER");
	
	if($current_version != BSC_CFS_VERSION) {
		$sql = "CREATE TABLE ".BSC_CFS_TABLE_NAME." (
				id INTEGER(11) AUTO_INCREMENT,
				field_name VARCHAR(255),
				data TEXT,
				type VARCHAR(255),
				custom_field_name VARCHAR(255),
				PRIMARY KEY (id) )
				CHARACTER SET UTF8";
		require_once(ABSPATH . "/wp-admin/includes/upgrade.php");
		dbDelta($sql);
		update_option("BSC_CFS_PLUGIN_VER",BSC_CFS_VERSION);
	}
	
}

function init_plugin() {

	wp_register_style("bsc_style.css",BSC_CFS_URL."/bsc_style.css");
	wp_enqueue_style("bsc_style.css");
	wp_register_script("bsc_script.js",BSC_CFS_URL."/bsc_script.js");
	wp_enqueue_script("bsc_script.js");
}



function remove_duplicate_item($data) {
	$data = array_unique($data);
	return $data;
}

function check_exist_id($id) {
	global $wpdb;
	$result = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".BSC_CFS_TABLE_NAME." WHERE id = %s",$id));
	return ($result > 0) ? true : false;
}

function load_data() {
	global $wpdb;
	$result = $wpdb->get_results("SELECT * FROM ".BSC_CFS_TABLE_NAME);
	if(count($result) > 0) {
		return $result;
	} else {
		return false;
	}
}

function load_get_latest_id() {
	global $wpdb;
	$result = $wpdb->get_var("SELECT id FROM ".BSC_CFS_TABLE_NAME." ORDER BY id DESC");
	$result = (int)$result + 1;
	echo $result;
	die();
}

add_action("wp_ajax_load_get_latest_id","load_get_latest_id");


function validate_obj($objs) {
	$errors_check = array();
	foreach($objs as $obj) 
	{
		if($obj->getData() == "") 
		{
			array_push($errors_check,"The data field can't be blank");
		}
		
	}
	return $errors_check;
}

function submit_data($objs) {
	$errors_check = array();
	if(empty($errors_check)) 
	{
		foreach($objs as $obj) 
		{
			if($obj->getID() != "" && (int)$obj->getID() > 0) 
			{
				update_field($obj->getField_name(),$obj->getData(),$obj->getType(),$obj->getID(),$obj->getCustom_field_name());
			} else 
			{
				insert_new_field($obj->getField_name(),$obj->getData(),$obj->getType(),$obj->getCustom_field_name()); 
			}
		}
		return true;
	}
	 else 
	{
		return $errors_check;	
	}
}


function load_search_options() {
	global $wpdb;
        $count_td_id = 0;
	$results = $wpdb->get_results("SELECT * FROM wp_bsc_custom_search");

	$wp_url = get_bloginfo('wpurl');

        if(get_bloginfo("language") == "vi"){
            $wp_url .= "/vi/";
        }

	$re = "<form method=\"get\" action='{$wp_url}'>";
		$re .= "<table width='100%' cellspacing='0' cellpadding='0' border='0'>";
			$re .= "<tbody>";
				$re .= "<tr>";
					$re .= "<th class=\"form_hr_left\" valign=\"middle\" scope=\"col\">".__($results[0]->field_name)."</th>";
					$re .= "<th width=\"20\" scope=\"col\"></th>";
					$re .= "<th class=\"form_hr_middle\" valign=\"middle\" scope=\"col\">".__($results[1]->field_name)."</th>";
				$re .= "</tr>";
				$re .= "<tr>";
				
					$re .= "<td class=\"form_td\" valign=\"top\">";
						$re .= "<table class=\"top_form\" width=\"100%\" border=\"0\">";
							$re .= "<tbody>";
								$re .= "<tr>";
									$data = unserialize($results[0]->data);
									for($i = 0;$i < count($data);$i++) {
									 
										$re .= "<td id={$count_td_id}>";
											if($results[0]->type == "checkbox") 
											{
												
												$re .= "<input id='{$data[$i]}-{$i}' type='checkbox' name='searchParam[{$results[0]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>";
                                                                                               
                                                                                                    $split_string = preg_split("[/]",$data[$i]);
                                                                                                    if(get_bloginfo("language") == "en-US") {
                                                                                                        $re .= $split_string[0];
                                                                                                    } else if(get_bloginfo("language") == "vi") {
                                                                                                         $re .= $split_string[1];
                                                                                                    }
                                                                                                $re .= "</label>";
											} else if($results[0]->type == "radio"){
												
												$re .= "<input id='{$data[$i]}-{$i}' type='radio' name='searchParam[{$results[0]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>{$data[$i]}</label>";
											}
										$re .= "</td>";
                                                                                $count_td_id++;
                                                                                
									}
								$re .= "</tr>";
							$re .= "<tbody>";
						$re .= "</table>";
					$re .= "</td>";
					
					$re .= "<td style=\"border-style:none;\">&nbsp;</td>";
					
					$re .= "<td class=\"form_td\" valign=\"top\">";
						$re .= "<table class=\"top_form\" width=\"100%\" border=\"0\">";
							$re .= "<tbody>";
								$re .= "<tr>";
									$data = unserialize($results[1]->data);
									for($i = 0;$i < count($data);$i++) {
										$re .= "<td id={$count_td_id}>";
											if($results[1]->type == "checkbox") 
											{
												
												$re .= "<input id='{$data[$i]}-{$i}' type='checkbox' name='searchParam[{$results[1]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>{$data[$i]}</label>";
											} else if($results[1]->type == "radio"){
												
												$re .= "<input id='{$data[$i]}-{$i}' type='radio' name='searchParam[{$results[1]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>";
                                                                                                    if($data[$i] == "All/Tất cả") 
                                                                                                    {
                                                                                                        $split_string = preg_split("[/]",$data[$i]);
                                                                                                        if(get_bloginfo("language") == "en-US") 
                                                                                                       {
                                                                                                            $re .= $split_string[0];
                                                                                                        } else if(get_bloginfo("language") == "vi") 
                                                                                                        {
                                                                                                             $re .= $split_string[1];
                                                                                                        }
                                                                                                    } else {
                                                                                                        $re .= $data[$i];
                                                                                                    }
                                                                                                $re .= "</label>";
											}
										$re .= "</td>";
                                                                                $count_td_id++;
									}
								$re .= "</tr>";
							$re .= "</tbody>";
						$re .= "</table>";
					$re .= "</td>";
					
					
				$re .= "</tr>";	
			$re .= "</tbody>";
		$re .= "</table>";	
		
		$re .= "<table class=\"maps_vn\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"margin-top:10px\">";
			$re.= "<tbody>";
				$re.="<tr>";
					$re.="<th class=\"form_hr_right\" valign=\"middle\" scope=\"col\">".__($results[2]->field_name)."</th>";
				$re .= "</tr>";
				$re .= "<tr>";
					$re .= "<td class=\"form_td\" valign=\"top\">";
						$re .= "<table class=\"top_form\" width=\"100%\" border=\"0\">";
							$re .= "<tr class=\"form_tr_1\">";
									$data = unserialize($results[2]->data);
									for($i = 0;$i < count($data);$i++) {
										$re .= "<td id={$count_td_id}>";
											if($results[2]->type == "checkbox") 
											{
												
												$re .= "<input id='{$data[$i]}-{$i}' type='checkbox' name='searchParam[{$results[2]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>";
                                                                                                     $split_string = preg_split("[/]",$data[$i]);
                                                                                                        if(get_bloginfo("language") == "en-US") 
                                                                                                       {
                                                                                                            $re .= $split_string[0];
                                                                                                        } else if(get_bloginfo("language") == "vi") 
                                                                                                        {
                                                                                                             $re .= $split_string[1];
                                                                                                        }
                                                                                                $re .= "</label>";
											} else if($results[2]->type == "radio"){
												
												$re .= "<input id='{$data[$i]}-{$i}' type='radio' name='searchParam[{$results[2]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>{$data[$i]}</label>";
											}
                                                                                        
										$re .= "</td>";
                                                                                $count_td_id++;
									}
							$re .= "</tr>";
							$re .= "<tr class=\"form_tr_2\">";
									$data = unserialize($results[3]->data);
									for($i = 0;$i < count($data);$i++) {
										$re .= "<td id=t_{$count_td_id}>";
											if($results[3]->type == "checkbox") 
											{
												
												$re .= "<input id='{$data[$i]}-{$i}' type='checkbox' name='searchParam[{$results[3]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>";
                                                                                                     $split_string = preg_split("[/]",$data[$i]);
                                                                                                        if(get_bloginfo("language") == "en-US") 
                                                                                                       {
                                                                                                            $re .= $split_string[0];
                                                                                                        } else if(get_bloginfo("language") == "vi") 
                                                                                                        {
                                                                                                             $re .= $split_string[1];
                                                                                                        }
                                                                                                $re .= "</label>";
											} else if($results[3]->type == "radio"){
												
												$re .= "<input id='{$data[$i]}-{$i}' type='radio' name='searchParam[{$results[3]->custom_field_name}][]' value='{$data[$i]}' class='search_checkbox' />";
												$re .= "<label for='{$data[$i]}-{$i}'>{$data[$i]}</label>";
											}
										$re .= "</td>";
                                                                                $count_td_id++;
									}
							$re .= "</tr>";
						$re .= "</table>";
					$re .= "</td>";
				$re .= "</tr>";		
		$re .= "</table>";
		$re .= "<input type='hidden' value='custom_search' name='s' />";
               
		$re .= "<div align='center'>";
			$re .= "<input type='submit' class='sendo' value='    ' />";
		$re .= "</div>";
	$re .= "</form>";
	return $re;
}


function side_bar_search() {
    $wp_url = get_bloginfo('wpurl');
    if(get_bloginfo("language") == "vi"){
            $wp_url .= "/vi/";
        }
    ?>
    <div class="search-sider">
          <h1 id="title_more_serach">
              <?php if(get_bloginfo("language") == "en-US") { echo "Advance Search";} else if(get_bloginfo("language") == "vi"){echo "Tìm kiếm nâng cao";}?>             
          </h1>
            <div id="more_serach_area">
    	<form method="get" action="<?php echo $wp_url; ?>">
        <h2><?php if(get_bloginfo("language") == "en-US") { echo "Price";} else if(get_bloginfo("language") == "vi"){echo "Giá";}?>            </h2>
		<select tabindex="1" name="searchParamSidebar[fromPrice]">
                    <option value="0" label="下限なし">
                         <?php
                            if(get_bloginfo("language") == "en-US") {
                                echo "Lowest";
                            } else if(get_bloginfo("language") == "vi"){
                                echo "Thấp nhất";
                            }
                         ?>  
                    </option>
                    <option value="500" label="500ドル">500USD</option>
                    <option value="1000" label="1000ドル">1000USD</option>
                    <option value="1500" label="1500ドル">1500USD</option>
                    <option value="2000" label="2000ドル">2000USD</option>
                    <option value="2500" label="2500ドル">2500USD</option>
                    <option value="3000" label="3000ドル">3000USD</option>
                </select>

                ～
		<select tabindex="2" name="searchParamSidebar[toPrice]">
                    <option value="999999" label="上限なし">
                         <?php
                            if(get_bloginfo("language") == "en-US") {
                                echo "Highest";
                            } else if(get_bloginfo("language") == "vi"){
                                echo "Cao nhất";
                            }
                         ?>  
                    </option>
                    <option value="500" label="500ドル">500USD</option>
                    <option value="1000" label="1000ドル">1000USD</option>
                    <option value="1500" label="1500ドル">1500USD</option>
                    <option value="2000" label="2000ドル">2000USD</option>
                    <option value="2500" label="2500ドル">2500USD</option>
                    <option value="3000" label="3000ドル">3000USD</option>
                </select>

			
                <h2> <?php if(get_bloginfo("language") == "en-US") { echo "Size";} else if(get_bloginfo("language") == "vi"){echo "Diện tích";}?>             </h2>
   		<select tabindex="3" name="searchParamSidebar[fromArea]">
                    <option value="0" label="下限なし">
                         <?php
                            if(get_bloginfo("language") == "en-US") {
                                echo "Lowest";
                            } else if(get_bloginfo("language") == "vi"){
                                echo "Thấp nhất";
                            }
                         ?>  
                    </option>
                    <option value="50" label="50㎡">50㎡</option>
                    <option value="60" label="60㎡">60㎡</option>
                    <option value="70" label="70㎡">70㎡</option>
                    <option value="80" label="80㎡">80㎡</option>
                    <option value="90" label="90㎡">90㎡</option>
                    <option value="100" label="100㎡">100㎡</option>
                </select>

                ～
   		<select tabindex="4" name="searchParamSidebar[toArea]">
                    <option value="999999" label="上限なし">
                         <?php
                            if(get_bloginfo("language") == "en-US") {
                                echo "Highest";
                            } else if(get_bloginfo("language") == "vi"){
                                echo "Cao nhất";
                            }
                         ?>  
                    </option>
                    <option value="50" label="50㎡">50㎡</option>
                    <option value="60" label="60㎡">60㎡</option>
                    <option value="70" label="70㎡">70㎡</option>
                    <option value="80" label="80㎡">80㎡</option>
                    <option value="90" label="90㎡">90㎡</option>
                    <option value="100" label="100㎡">100㎡</option>
                </select>

           <h2>
                <?php
                    if(get_bloginfo("language") == "en-US") {
                        echo "Keyword";
                    } else if(get_bloginfo("language") == "vi"){
                        echo "Từ khóa";
                    }
               ?>  
           </h2>
               <input type="text" style="width:210px;margin:10px 0 20px;" tabindex="5" value="" name="searchParamSidebar[keyword]">
                <input type='hidden' value='custom_search' name='s' /><br />
                <input type="submit" style="background: url('<?php if(get_bloginfo("language") == "en-US") { echo get_bloginfo('wpurl')."/wp-content/themes/Creation/images/serach_btn.jpg"; } else if(get_bloginfo("language") == "vi") { echo get_bloginfo('wpurl')."/wp-content/themes/Creation/images/serach_btn_vi.jpg"; }?>') ; border:none; width:162px; height:24px;" value="" alt="この条件で検索">
            </form>
            </div>
           </div>
    <?php
}

function override_search($where) 
{
	
		if(is_search()) 
		{
                    if(isset($_GET['searchParam'])) 
                    {
                   
                        $count = 1;
			$where = " AND wp_posts.ID IN (SELECT DISTINCT post_id FROM wp_postmeta WHERE post_id IN ";
			foreach($_GET['searchParam'] as $key => $value) 
                        {
				
				$where .= "(SELECT post_id FROM wp_postmeta WHERE ";
				if($key == "textfield_price" && count($value) == 1 && $value[0] == "All/Tất cả") 
				{
					$where .= "meta_key = '{$key}' AND meta_value BETWEEN 0 AND 999999999";
				} else if($key == "textfield_price" && $value[0] != "All/Tất cả")
                                {
                                        $value[0] = preg_replace("/[USD]/",'',$value[0]);
                                        $value[0] = preg_replace("/[>]/",'',$value[0]);
                                        if(preg_match("/[～]/",$value[0])) 
                                        {
                                          
                                            $split_string_price = preg_split("/[～]/",$value[0]);
                                            
                                            $fromPrice = $split_string_price[0];
                                            $toPrice = $split_string_price[3];
                                            $where .= "meta_key = '{$key}' AND meta_value BETWEEN {$fromPrice} AND {$toPrice}";
                                        } 
                                        else 
                                        {
                                          
                                            $where .= "meta_key = '{$key}' AND meta_value > {$value[0]}";
                                        }
				
				} 
                                else if($key == "select_area" && $value[0] == "Other/Khác") 
                                {
                                    $where .= "meta_key = '{$key}' AND meta_value = 'Other/Khác'";
                                }
                                else if($key == "select_area" && $value[0] == "All/Tất cả") 
                                {
                                    $where .= "post_id IN (SELECT post_id FROM wp_postmeta)";
                                }
                                else 
                                {
                                        $where .= "meta_key = '{$key}' AND meta_value IN ('".implode("','",$value)."')";
                                }
					if($count == count($_GET['searchParam']))
					{
						$where .= ")";
					} 
					else 
					{
						$where .= ") AND post_id IN ";
					}
					
					$count++;
				
				
				
			}
			$where .= ") AND wp_posts.post_status = 'publish' AND wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = 5)";
                     
                    
			
                    }
                    else if(isset($_GET['searchParamSidebar'])) 
                    {
                      
                        $where = " AND wp_posts.post_status = 'publish' AND wp_posts.ID IN (SELECT DISTINCT post_id FROM wp_postmeta WHERE post_id IN (SELECT post_id FROM wp_postmeta WHERE meta_key = 'textfield_price' AND meta_value BETWEEN ".$_GET['searchParamSidebar']['fromPrice']." AND ".$_GET['searchParamSidebar']['toPrice'].") AND post_id IN (SELECT post_id FROM wp_postmeta WHERE meta_key = 'textfield_size' AND meta_value BETWEEN ".$_GET['searchParamSidebar']['fromArea']." AND ".$_GET['searchParamSidebar']['toArea'].") AND post_id IN (SELECT ID FROM wp_posts WHERE post_title LIKE '%{$_GET['searchParamSidebar']['keyword']}%')) AND wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = 5)";
                    }
                    else 
                    {
                        $where = " AND wp_posts.post_status = 'publish' AND wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = 5)";
                    }
           
                }

	return $where;
}

add_filter("posts_where","override_search");


add_shortcode("load-search-options", "load_search_options");
add_shortcode("load-search-options-sidebar", "side_bar_search");
function load_custom_field() {
	global $wpdb;
	$results = $wpdb->get_results("SELECT DISTINCT meta_key FROM wp_postmeta WHERE meta_key NOT REGEXP '^[_]'");
	return $results;
}

function insert_new_field($field_name,$data,$type,$custom_field_name) {
	global $wpdb;
	return $result = $wpdb->insert(BSC_CFS_TABLE_NAME,
										array("field_name" => $field_name,"data" => $data,"type" => $type, "custom_field_name" => $custom_field_name),
										array("%s","%s","%s","%s")); 
}

function update_field($field_name,$data,$type,$id,$custom_field_name) {
	global $wpdb;
	return $result = $wpdb->update(BSC_CFS_TABLE_NAME,
										array("field_name" => $field_name,"data" => $data,"type" => $type, "custom_field_name" => $custom_field_name),
										array("id" => $id),
										array("%s","%s","%s","%s"),array("%s"));
}


register_activation_hook(__FILE__, "plugin_installation");
add_action("admin_init","init_plugin");
require_once(dirname(__FILE__)."/bsc_custom_field_class.php");
require_once(dirname(__FILE__)."/bsc_custom_field_search_admin.php");
